package com.ls.lserp.modules.material.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ls.lserp.modules.sys.utils.SystemMessageUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.material.entity.InventoryRequest;
import com.ls.lserp.modules.material.service.InventoryRequestService;
import com.ls.lserp.modules.setting.entity.Ognization;
import com.ls.lserp.modules.sys.entity.User;
import com.ls.lserp.modules.sys.utils.SequenceUtil;
import com.ls.lserp.modules.trade.entity.Enchase;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/inventory/request/")
public class InventoryRequestController extends BaseController {

	// 保存 编辑 删除 方法
	@Autowired
	private InventoryRequestService inventoryRequestService;
	@Autowired
	Configuration freemarkerConfiguration;

	@ModelAttribute
	public InventoryRequest get(@RequestParam(required = false) String id) {

		// 判断id是否为空
		if (StringUtils.isNotBlank(id)) {
			// 执行查询语句 查询基本信息
			return inventoryRequestService.get(Long.parseLong(id));
		} else {
			// 若为空，实例化
			return new InventoryRequest();
		}
	}

	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("inventory:request:view")
	@RequestMapping(value = { "" })
	public String list(Model model) {
		// 画面跳转
		return "modules/material/inventoryRequest";
	}

	/**
	 * @Title: 画面检索
	 * @Description: 查询页面
	 * @param inventoryRequest
	 * @param request
	 * @param response
	 * @param model
	 * @return searchList
	 * @throws Exception
	 */
	@RequiresPermissions("inventory:request:view")
	@RequestMapping(value = { "searchList" })
	@ResponseBody
	public String searchList(InventoryRequest inventoryRequest, HttpServletRequest request, HttpServletResponse response,
			Model model) throws Exception {
		Map<Object, Object> listMap = new HashMap<Object, Object>();
		// ajax回调时使用的一览list名
		request.setAttribute(Global.LIST_NAME, "inventoryRequest");
		// 拼接字符串供分页使用
		StringBuilder searchParam = new StringBuilder();
		// 客户名称
		searchParam.append("&venderName=");
		searchParam.append(inventoryRequest.getVenderName());
		// 日期
		searchParam.append("&dateFrom=");
		searchParam.append(inventoryRequest.getDateFrom());
		searchParam.append("&dateTo=");
		searchParam.append(inventoryRequest.getDateTo());
		// 状态
		searchParam.append("&tabPageStatus=");
		searchParam.append(inventoryRequest.getTabPageStatus());
		// 放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
		request.setAttribute(Global.SEARCH_PAEAM, searchParam.toString());
		
		// 查询一览页面数据
		Page<InventoryRequest> page = inventoryRequestService.findList(new Page<InventoryRequest>(request, response),inventoryRequest);
		// 读取系统路径
		String strUri = request.getContextPath() + Global.getAdminPath();
		// 读取文件生成字符串
		String strHtml = "";
		Map<String, Object> map = new HashedMap();
		map.put("adminUri", strUri);
		map.put("inventoryRequests", page.getList());
		map.put("pageNo", page.getPageNo());
		map.put("pageSize", page.getPageSize());
		strHtml = FreeMarkerTemplateUtils
				.processTemplateIntoString(freemarkerConfiguration.getTemplate("inventoryRequest.ftl"), map);
		listMap.put("inventoryRequest", strHtml);
		listMap.put("page", page.getHtml());

		// ajax返回结果
		return renderString(response, listMap);
	}
	
	/**
	 * 进入编辑页面
	 * @param ognization
	 * @param model
	 * @return
	 */
	@RequiresPermissions("inventory:request:edit")
	@RequestMapping(value = "form")
	public String form(InventoryRequest inventoryRequest,RedirectAttributes redirectAttributes, Model model,HttpSession session) {
		
		// 获取当前用户
		User curLoginUser = inventoryRequest.getCurrentUser();
		
		// 下拉列表客户名称取得
		Ognization paramOgnization = new Ognization();
		//账户类型（1、平台账户；2、店铺账户；3、加工厂账户；4、供货商账户；5、客户；）
		paramOgnization.setOgnizationType(5L);
		paramOgnization.setCurrentUser(curLoginUser);
		inventoryRequest.setVenderList(inventoryRequestService.selVenderList(paramOgnization));
		
		if(inventoryRequest.getId() == null){
			// 入库单条码
			inventoryRequest.setStockBarCode(SequenceUtil.inventoryRequestbarcode().getReturnCode());
			
			// 申请人
			inventoryRequest.setRequestUser(curLoginUser.getFirstName() + curLoginUser.getLastName());
			inventoryRequest.setRequestUserId(curLoginUser.getId());
			
			// 申请日期
			inventoryRequest.setRequestDate(new Date());
			
			// 下拉菜单（客供入库）
			inventoryRequest.setInventoryCategory(ResourcesUtil.getConfig("inventory_category_customer"));
			 model.addAttribute("sequenceReturnCode", SequenceUtil.inventoryRequest().getReturnCode());
		}else{
		   	   // 查找入库申请明细
			   List<InventoryRequest> resultRequestList = inventoryRequestService.findRequestDetailsList(inventoryRequest);
			   inventoryRequest.setRequestDetailsList(resultRequestList);
			   
			   if(inventoryRequest.getVenderId() != null){
			    	/*前台返回国家code值写入code，调用方法查询code值下的城市列表*/
			        List<InventoryRequest> brandList=inventoryRequestService.findBrand(inventoryRequest.getVenderId().toString());
			        inventoryRequest.setBrandList(brandList);
			   }
		}
		
		// 将实体类值赋给mvc model层返回jsp页面
		model.addAttribute("inventoryRequest", inventoryRequest);
		
		// 返回页面地址
		return "modules/material/inventoryRequestCreate";
	}
	
	/**
     * 联动返回城市
     * @param user
     * @param model
     * @return
     */
    @RequiresPermissions("inventory:request:view")
    @RequestMapping(value = "brand")
    @ResponseBody
    public String findBrand(String venderId,Model model,HttpServletResponse response ) {
    	
    	/*前台返回国家code值写入code，调用方法查询code值下的城市列表*/
        List<InventoryRequest> brandList=inventoryRequestService.findBrand(venderId);
        
        return renderString(response, brandList);
       
    }
    
    /**
     * @Title: delRequestDetail
     * @Description: 删除入库申请明细
     * @param @param inventoryRequest
     * @param @param model
     * @param @param session
     * @param @return
     * @return String 
     * @throws
     */

   @RequiresPermissions("inventory:request:edit")
   @RequestMapping(value = "delRequestDetails")
   public String delRequestDetail(InventoryRequest inventoryRequest, HttpServletRequest request, HttpServletResponse response, Model model) {
       try {
     	  
    	   inventoryRequest.getRequestDetailsList().remove(inventoryRequest.getTrIndex());
    	   
   	       // 将page值赋值给mvc model层返回jsp页面
      	   model.addAttribute("inventoryRequest", inventoryRequest);
   	    
          // 返回地址
          return "modules/material/inventoryRequestCreate";
       } catch (Exception e) {
           // 记录日志
           logger.error(e.getMessage(), e);
           // 返回地址
           return "modules/material/inventoryRequestCreate";
       }
   }
   
   /**
    * 保存信息
    * @param enchase
    * @param request
    * @param model
    * @param response
    * @return
    * @throws ResourceException 
    */
   @RequiresPermissions("inventory:request:edit")
   @RequestMapping(value = "save")
   @ResponseBody
   public String save(InventoryRequest inventoryRequest, HttpServletRequest request, Model model, HttpServletResponse response , HttpSession session) throws ResourceException {

		// 判断id是否为null （判断新建或修改）
		if(inventoryRequest.getId()!=null){
			// 编辑数据
			// 判断数据是否删除
			InventoryRequest inventoryRequestNew = get(inventoryRequest.getId().toString());
			// 判断数据是否删除
           if(inventoryRequestNew==null || BaseEntity.DEL_FLAG_DELETE.equals(inventoryRequestNew.getDeleteFlag())){
           	// 返回提示信息
           	return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
           }
			
           // 排他处理
		    if(inventoryRequest.getVersion()==get(inventoryRequest.getId().toString()).getVersion()){
		    	
		    	// 版本号加1
		    	inventoryRequest.setVersion(inventoryRequest.getVersion()+1);
		    }else{
		    	
		    	// 返回提示信息
		        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		    }
		}
	   
   	   // 保存入库申请
	   inventoryRequestService.saveInventoryRequest(inventoryRequest);
   	
   	   // 保存成功返回提示信息
       return renderString(response,AjaxDone.ok(SystemMessageUtils.getMessageName( "inventory_request_save_success")));
   }
   
	/**
    * 进入查看页面
    * @param inventoryRequest
    * @param model
    * @return
    */
   @RequiresPermissions("inventory:request:view")
   @RequestMapping(value = "show")
   public String show(InventoryRequest inventoryRequest, Model model) {
	   
   	   // 查找入库申请明细
	   List<InventoryRequest> resultRequestList = inventoryRequestService.findRequestDetailsList(inventoryRequest);
	   inventoryRequest.setRequestDetailsList(resultRequestList);
   	
       // 将查询结果赋值mvc model层返回jsp页面
       model.addAttribute("inventoryRequest", inventoryRequest);
       
       // 返回页面地址
       return "modules/material/inventoryRequestShow";
   }
    
    /**
     * @Title: 2017-04
     * @Description: 添加入库申请明细
     * @param @param addRequestDetails
     * @param @param model
     * @param @param session
     * @param @return
     * @return String 
     * @throws
     */

   @RequiresPermissions("inventory:request:edit")
   @RequestMapping(value = "addRequestDetails")
   public String addRequestDetails(InventoryRequest inventoryRequest, HttpServletRequest request, HttpServletResponse response, Model model) {
       try {
     	  
   	       // 将page值赋值给mvc model层返回jsp页面
      	   model.addAttribute("inventoryRequest", inventoryRequest);
      	  
   	    
          // 返回地址
          return "modules/material/inventoryRequestCreate";
       } catch (Exception e) {
           // 记录日志
           logger.error(e.getMessage(), e);
           
           // 返回地址
           return "modules/material/inventoryRequestCreate";
       }
   }
   
   /**
    * @Title: delRequestDetail
    * @Description: 删除入库申请明细
    * @param @param inventoryRequest
    * @param @param model
    * @param @param session
    * @param @return
    * @return String 
    * @throws
    */

  @RequiresPermissions("inventory:request:edit")
  @RequestMapping(value = "delAllDetails")
  public String delAllDetails(InventoryRequest inventoryRequest, HttpServletRequest request, HttpServletResponse response, Model model) {
      try {
    	  
    	  inventoryRequest.setRequestDetailsList(new ArrayList<InventoryRequest>());
   	   
  	       // 将page值赋值给mvc model层返回jsp页面
     	   model.addAttribute("inventoryRequest", inventoryRequest);
  	    
         // 返回地址
         return "modules/material/inventoryRequestCreate";
      } catch (Exception e) {
          // 记录日志
          logger.error(e.getMessage(), e);
          // 返回地址
          return "modules/material/inventoryRequestCreate";
      }
  }
}
